<?php
namespace app\common\middleware;
use app\common\model\User as UserModel;
use think\Facade\Cache;
use think\Facade\Env;
use think\Facade\Session;
use think\Facade\View;

error_reporting(0);

class CheckLogin {
	public function handle($request, \Closure $next) {
		//获取setting
		if (!Cache::has('settings')) {
			$request->settings = \app\common\model\Setting::getAll();
		} else {
			$request->settings = Cache::get('settings');
		}
		View::assign('settings', $request->settings);
		if (!strstr(strtolower($request->server('REQUEST_URI')), '/index/index/login')) {
			//dump(strstr(strtolower($request->server('REQUEST_URI')), '/index/user/login'));
			if (!Session::has('user') && Env::has('AUTO_LOGIN')) {
				Session::set('user', UserModel::find(Env::get('AUTO_LOGIN')));
			}
			if (Session::has('user')) {
				$sUser = Session::get('user');
				$user = UserModel::find($sUser['user_id']);
				if (!$user || $user->password != $sUser['password'] || $user->status == 0) {
					Session::delete('user');
				} else {
					Session::set('user', $user);
					$request->user_id = $user->user_id;
					$request->user = $user;
					return $next($request);
				}
			}
			return redirect('/Index/Index/Login');
		}
		return $next($request);
	}
}